import { Context } from 'egg';
import BaseController from '../public/BaseController';
export default class UserController extends BaseController {

  constructor(ctx: Context) {
    super(ctx);
  }

  public async userInfo() {
    const { ctx } = this;
    const { _id: userId } = ctx.user;
    const existsUser = await ctx.model.User.findById(userId);
    this.success(existsUser);
  }

  public async create() {
    const { ctx } = this;
    const { username, password } = ctx.request.body;
    const existsUser = await ctx.model.User.findOne({ username });
    if (existsUser) {
      this.fail(450, '改用户已经存在');
    }

    const newUser = await ctx.model.User.create({ username, password });
    this.success(newUser);
  }

  public async logout() {
    const { ctx } = this;
    await ctx.logout();
    this.success();
  }
}
